<?php



if (!function_exists('aB_to_a_b')) {
    /**
     * 驼峰转下划线
     * @param string $string
     * @return string
     */
    function aB_to_a_b(string $string)
    {
        return strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $string));
    }
}

if (!function_exists('flash')) {
    function flash($message, $level = 'warning')
    {
        $message = new \Illuminate\Support\MessageBag([$level => $message]);
        request()->session()->flash($level, $message);
    }
}

if (!function_exists('get_first_flash')) {
    /**
     * 获取第一条FLASH信息.
     *
     * @param $level
     *
     * @return mixed|string
     */
    function get_first_flash($level)
    {
        if ($level === 'error' && session('errors') && session('errors')->any()) {
            return session('errors')->all()[0];
        }
        if (!session()->has($level)) {
            return '';
        }

        return session($level)->first();
    }
}
if (!function_exists('menu_active')) {
    /**
     * @param $routeName
     *
     * @return bool
     */
    function menu_active($routeName)
    {
        return request()->routeIs($routeName) ? 'active' : '';
    }
}

if (!function_exists('exception_record')) {
    /**
     * 记录异常.
     *
     * @param Exception $exception
     */
    function exception_record(Exception $exception): void
    {
        $request = request();
        $data = [
            'message' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'code' => $exception->getCode(),
            'line' => $exception->getLine(),
            'params' => $request->all(),
            'url' => $request->url(),
            'method' => $request->method(),
            'ip' => $request->getClientIps(),
        ];
        \Log::error('exception', $data);
    }
}

if (!function_exists('markdown_to_html')) {
    /**
     * markdown转换为html.
     *
     * @param $content
     *
     * @return string
     */
    function markdown_to_html($content)
    {
        $content = (new Parsedown())->setBreaksEnabled(true)->parse($content);
        $content = clean($content);
        $content = preg_replace('#<table>#', '<table class="table table-hover table-bordered">', $content);

        return $content;
    }
}

if (!function_exists('aliyun_sdk_client')) {
    function aliyun_sdk_client()
    {
        /**
         * @var \App\Services\Base\Services\ConfigService $configService
         */
        $configService = app()->make(\App\Services\Base\Interfaces\ConfigServiceInterface::class);
        $aliyunVodConfig = $configService->getAliyunVodConfig();
        \AlibabaCloud\Client\AlibabaCloud::accessKeyClient($aliyunVodConfig['access_key_id'], $aliyunVodConfig['access_key_secret'])
            ->regionId($aliyunVodConfig['region'])
            ->connectTimeout(1)
            ->timeout(15)
            ->asDefaultClient();
    }
}

if (!function_exists('aliyun_assumeRole')) {

    /**
     * 提供AssumeRole API的PHP SDK
     */
    function aliyun_assumeRole()
    {
        try {
            aliyun_sdk_client_for_oss();
            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->product('Sts')
                ->scheme('https') // https | http 解决InvalidProtocol.NeedSsl
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => 'oss-cn-qingdao',
                        'RoleArn' => "acs:ram::1395923275437140:role/sxyaliyunossrole",
                        'RoleSessionName' => "alice",
                    ],
                ])
                ->request();
//            dd($result->toArray());
            return $result->toArray();
        } catch (Exception $exception) {
            exception_record($exception);
            return [];
        }
    }
}

if (!function_exists('aliyun_sdk_client_for_oss')) {
    function aliyun_sdk_client_for_oss()
    {
        /**
         * @var \App\Services\Base\Services\ConfigService $configService
         */
        $configService = app()->make(\App\Services\Base\Interfaces\ConfigServiceInterface::class);
        $aliyunOssConfig = $configService->getAliyunOssConfig();
        \AlibabaCloud\Client\AlibabaCloud::accessKeyClient($aliyunOssConfig['access_id'], $aliyunOssConfig['access_key'])
            ->regionId('oss-cn-qingdao')
            ->connectTimeout(1)
            ->timeout(15)
            ->asDefaultClient();
    }
}

use EasyDingTalk\Application;
if (!function_exists('dingTalk_sdk_application')) {
    /**
     * 钉钉SDK
     * @return Application
     */
    function dingTalk_sdk_application()
    {
        $config = [
            'corp_id' => 'ding79af88f09b0f7278',//广东卡诺亚家居有限公司
            'app_key' => 'dingoo0k50llv70nz3ql',//企业内部开发---H5微应用---卡诺亚商学院
            'app_secret' => 'DCTD7kuBcFeMCvggUOo80T6biU4_eDMKb7upD-FfLhC5To3VYk075FoWyqcxgd_k',//企业内部开发---H5微应用---卡诺亚商学院
            'agent_id' => '1143895610',//企业内部开发---H5微应用---卡诺亚商学院
        ];

        $app = new Application($config);

        return $app;
    }
}
if (!function_exists('dingTalk_sdk_application_erp')) {
    /**
     * 钉钉SDK
     * @return Application
     */
    function dingTalk_sdk_application_erp()
    {
        $config = [
            'corp_id' => 'ding79af88f09b0f7278',//广东卡诺亚家居有限公司
            'app_key' => 'dingtm7z2xs5kut5zu4n',//企业内部开发---H5微应用---H5版ERP
            'app_secret' => 'fhJxV-mObRTOYxR0gV20WAmXF6NH-lo5hEQR0g7w7VC73nPMIllo5GxxLBBx7i0D',//企业内部开发---H5微应用---H5版ERP
            'agent_id' => '758856846',//企业内部开发---H5微应用---H5版ERP
        ];

        $app = new Application($config);

        return $app;
    }
}

if (!function_exists('is_h5')) {
    /**
     * @return bool
     */
    function is_h5()
    {
        return (new Mobile_Detect())->isMobile();
    }
}

if (!function_exists('is_wechat')) {
    /**
     * @return bool
     */
    function is_wechat()
    {
        if (strpos(request()->server('HTTP_USER_AGENT'), 'MicroMessenger')) {
            return true;
        }
        return false;
    }
}

if (!function_exists('duration_humans')) {
    /**
     * 把秒数转化为时间,intdiv() 函数，接收两个参数，返回值为第一个参数除于第二个参数的值并取整。
     * @param $duration
     *
     * @return string
     */
    function duration_humans($duration)
    {
        $minute = intdiv($duration, 60);//获取分钟数
        $second = $duration % 60;//获取除不尽的秒数
        if ($minute >= 60) {
            $hours = intdiv($minute, 60);//获取小时数
            $minute %= 60;//获取除不尽的分钟数

            return sprintf('%02d:%02d:%02d', $hours, $minute, $second);
        }

        return $minute ? sprintf('00:%02d:%02d', $minute, $second) : sprintf('00:00:%02d', $second);
    }
}

if (!function_exists('enabled_socialites')) {
    /**
     * 获取已启用的第三方登录.
     *
     * @return \Illuminate\Support\Collection
     */
    function enabled_socialites()
    {
        $socialites = config('meedu.member.socialite', []);
        $enabled = collect($socialites)->filter(function ($item) {
            return (int)$item['enabled'] === 1;
        });

        return $enabled;
    }
}

if (!function_exists('get_at_users')) {
    /**
     * @param string $content
     * @return array
     */
    function get_at_users(string $content): array
    {
        preg_match_all('/@(.*?)\s{1}/', $content, $result);
        if (count($result[1] ?? []) === 0) {
            return [];
        }
        return $result[1];
    }
}

if (!function_exists('array_compress')) {
    /**
     * 多维数组中子数组的key形成了祖先路径字符串
     * @param array $arr
     * @param string $prevKey
     * @return array
     */
    function array_compress(array $arr, string $prevKey = ''): array
    {
        $rows = [];
        foreach ($arr as $key => $item) {
            $tmpKey = ($prevKey ? $prevKey . '.' : '') . $key;
            if (is_array($item)) {
                $rows = array_merge($rows, array_compress($item, $tmpKey));
            } else {
                $rows[$tmpKey] = $item;
            }
        }
        return $rows;
    }
}

if (!function_exists('random_number')) {
    /**
     * @param $prefix
     * @param $length
     * @return string
     * @throws Exception
     */
    function random_number($prefix, $length): string
    {
        $prefixLength = mb_strlen($prefix);
        $length -= $prefixLength;
        for ($i = 0; $i < $length; $i++) {
            $prefix .= random_int(0, 9);
        }
        return $prefix;
    }
}

if (!function_exists('decode_records_json')) {

    /**
     * 深度处理json字符串，原处变为数组
     * @param $records
     * @param $keyArray
     * @param array $default
     */
    function decode_records_json(&$records, $keyArray, $default = [])
    {
        if (empty($records)) {
            return;
        }
        if (is_string($keyArray)) {
            $keyArray = [$keyArray];
        }
        foreach ($records as &$record) {
            foreach ($keyArray as $key) {
                $record[$key] = json_decode($record[$key], true);
                if (empty($record[$key])) {
                    $record[$key] = $default;
                }
            }
        }
    }
}

if (!function_exists('arr1_clear')) {
    /**
     * 函数只返回给定数组中指定的键值对：
     * @param $arr
     * @param $columns
     * @return array
     */
    function arr1_clear($arr, $columns)
    {
        return \Illuminate\Support\Arr::only($arr, $columns);
    }
}

if (!function_exists('arr2_clear')) {
    /**
     * 函数只返回给定数组中第一重循环或者第二重循环指定的键值对：
     * @param $arr
     * @param $columns
     * @param bool $rec
     * @return array
     */
    function arr2_clear($arr, $columns, $rec = false)
    {
        return array_map(function ($item) use ($columns, $rec) {
            if (!$rec) {//默认第一重循环
                return \Illuminate\Support\Arr::only($item, $columns);
            }
            return array_map(function ($item) use ($columns) {//$rec赋值true时使用第二重循环
                return \Illuminate\Support\Arr::only($item, $columns);
            }, $item);
        }, $arr);
    }
}

if (!function_exists('is_dev')) {
    /**
     * @return bool|string
     */
    function is_dev()
    {
        return app()->environment(['dev', 'local']);
    }
}

if (!function_exists('get_array_ids')) {
    /**
     * @param array $data
     * @param string $key
     * @return array
     */
    function get_array_ids(array $data, string $key = 'id'): array
    {
        $ids = [];
        foreach ($data as $item) {
            $id = $item[$key] ?? false;
            if ($id === false) {
                continue;
            }
            $ids[$id] = 0;
        }
        return array_keys($ids);
    }
}

if (!function_exists('get_platform')) {
    /**
     * @return array|string|null
     */
    function get_platform()
    {
        // 如果默认读取不到，则将平台统一设置为 ‘PC’
        $platform = strtoupper(request()->header('eduPlatform', \App\Constant\FrontendConstant::LOGIN_PLATFORM_PC));
        $platforms = [
            \App\Constant\FrontendConstant::LOGIN_PLATFORM_APP,
            \App\Constant\FrontendConstant::LOGIN_PLATFORM_PC,
            \App\Constant\FrontendConstant::LOGIN_PLATFORM_H5,
            \App\Constant\FrontendConstant::LOGIN_PLATFORM_IOS,
            \App\Constant\FrontendConstant::LOGIN_PLATFORM_ANDROID,
            \App\Constant\FrontendConstant::LOGIN_PLATFORM_MINI,
            \App\Constant\FrontendConstant::LOGIN_PLATFORM_OTHER,
        ];
        if (!in_array($platform, $platforms)) {
            $platform = \App\Constant\FrontendConstant::LOGIN_PLATFORM_PC;
        }
        return $platform;
    }
}

if (!function_exists('html_to_text')) {
    /**
     * 把html转化为纯text，可以限定长度
     * @param $content
     * @param null $limit
     * @return string
     */
    function html_to_text($content, $limit = null): string
    {
        $text = preg_replace('/<[^>]+>/', '', $content);
        if (null !== $limit) {
            $text = \Illuminate\Support\Str::limit($text, $limit);
        }
        return html_entity_decode($text);//反转义html
    }
}

if (!function_exists('mbStrSplit')) {
    /**
     * 支持中文的PHP按字符串长度分割成数组代码
     * @param $string
     * @param int $len
     * @return array
     */
    function mbStrSplit ($string, $len=1) {
        $start = 0;
        $strlen = mb_strlen($string);
        $array = [];
        while ($strlen) {
            $array[] = mb_substr($string,$start,$len,"utf8");
            $string = mb_substr($string, $len, $strlen,"utf8");
            $strlen = mb_strlen($string);
        }
        return $array;
    }
}

if (!function_exists('save_image')) {
    function save_image($file): array
    {
        /**
         * @var $configService \App\Services\Base\Services\ConfigService
         */
        $configService = app()->make(\App\Services\Base\Interfaces\ConfigServiceInterface::class);
        $disk = $configService->getImageStorageDisk();
        /**
         * @var \Illuminate\Http\UploadedFile $file
         */
        $path = $file->store($configService->getImageStoragePath(), compact('disk'));
        $url = url(\Illuminate\Support\Facades\Storage::disk($disk)->url($path));
        $data = compact('path', 'url', 'disk');
        $data['encryptData'] = $encryptData = encrypt(json_encode($data));
        return $data;
    }
}

if (!function_exists('save_aiwenjuan')) {
    function save_aiwenjuan($file): array
    {
        /**
         * @var $configService \App\Services\Base\Services\ConfigService
         */
        $configService = app()->make(\App\Services\Base\Interfaces\ConfigServiceInterface::class);
        $disk = $configService->getAiwenjuanStorageDisk();
        /**
         * @var \Illuminate\Http\UploadedFile $file
         */
        
        $path = $file->store($configService->getAiwenjuanStoragePath(), compact('disk'));
        $url = url(\Illuminate\Support\Facades\Storage::disk($disk)->url($path));
        $data = compact('path', 'url', 'disk');
        $data['encryptData'] = $encryptData = encrypt(json_encode($data));
        return $data;
    }
}

if (!function_exists('get_cache_key')) {
    /**
     * @param $key
     * @param mixed ...$params
     * @return string
     */
    function get_cache_key(string $key, ...$params): string
    {
        return sprintf($key, ...$params);
    }
}

if (!function_exists('str_to_utf8')) {
    function str_to_utf8 ($str = '') {
        $current_encode = mb_detect_encoding($str, array("ASCII","GB2312","GBK",'BIG5','UTF-8'));
        $encoded_str = mb_convert_encoding($str, 'UTF-8', $current_encode);
        return $encoded_str;
    }
}

if (!function_exists('getOssClient')) {
    function getOssClient ($str = '') {
        try {
            $ossClient = new OSS\OssClient('cjQsDX9bON3Pgzyc', 'SiMJZHubzULQ7Wlgiwwrm3zmL8ToG5', 'oss-cn-qingdao.aliyuncs.com');
        } catch (\Exception $e) {
        }
        return $ossClient;
        
    }
}

if (!function_exists('getSignUrl')) {
    function getSignUrl ($ossClient,$url) {
        $local_path = str_replace('localossfs://', '', $url);
        $signUrl = $ossClient->signUrl('knoya-qd',$local_path,'86400');
        return $signUrl;
    }
}
